package net.app.zoneland.file;

import io.minio.PutObjectOptions;
import io.minio.errors.*;
import lombok.AllArgsConstructor;
import net.app.zoneland.common.core.vo.Result;
import net.app.zoneland.file.utils.MinIoUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.util.UriUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;

/**
 * @Description
 * @Author LENOVO
 * @CreateTime 2021/1/1 1:54
 * @Version: 1.0
 */
@RestController
@RequestMapping("/minio")
@AllArgsConstructor
public class MinioController {

    private final MinIoUtils minIoUtils;

    /**
     * 上传文件
     * @return
     */
    @PostMapping("/upload")
    public Result upload(HttpServletRequest request) {
       try {
           // 创建一个通用的多部分解析器
           CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
           // 判断 request 是否有文件上传,即多部分请求
           if (multipartResolver.isMultipart(request)) {
               // 转换成多部分request
               MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
               // 取得request中的所有文件名
               Iterator<String> iter = multiRequest.getFileNames();
               while (iter.hasNext()) {
                   MultipartFile importFile = multiRequest.getFile(iter.next());
                   //文件名
                   String fileName = importFile.getOriginalFilename();
                   InputStream inputStream=importFile.getInputStream();
                   if(!minIoUtils.bucketExists("test")){
                       minIoUtils.makeBucket("test");
                   }
                   // PutObjectOptions，上传配置(文件大小，内存中文件分片大小)
                   PutObjectOptions options = new PutObjectOptions(importFile.getSize(), PutObjectOptions.MIN_MULTIPART_SIZE);
                   options.setContentType(importFile.getContentType());
                   minIoUtils.putObject("test", fileName, inputStream,options);
                   String encode = UriUtils.encode(fileName, StandardCharsets.UTF_8);
                   System.out.println("返回路径："+encode);
               }
           }
           return Result.success();
       }catch (Exception e){
           e.printStackTrace();
           return Result.error("上传文件出错!");
       }
    }
}
